package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: HuangFu
 * @Date: 2020/2/2 19:33
 * @Description: 商品查询
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Override
    public Map search(Map<String, String> searchMap) throws Exception {
        Map<String, Object> resultMap = new HashMap<>(16);
        if(searchMap !=null){
            //创建查询对象
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //设置查询关键词
            if(!StringUtils.isEmpty(searchMap.get("keywords"))){
                boolQuery.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
            }
            //设置品牌查询条件
            if(!StringUtils.isEmpty(searchMap.get("brand"))){
               boolQuery.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
            }
            //设置规格查询条件
            for (String key : searchMap.keySet()) {
                if(key.startsWith("spec_")){
                    boolQuery.filter(QueryBuilders.termQuery("specMap."+ key.substring(5) + ".keyword",searchMap.get(key)));
                }
            }
            //设置价格查询条件,区间数据  x< price <y
            if(!StringUtils.isEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
                //get地板
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
                if(prices.length==2){
                   //lte天花板
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
            }

            //创建原生收索实现类
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQuery);

            //高亮设置
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);

            //品牌聚合分组查询
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //规格聚合分组查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //数据排序
            if(StringUtils.isNotEmpty(searchMap.get("sortField"))){
                if("ASC".equals(searchMap.get("sortRule"))){
                    //升序排序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                }else {
                    //降序排序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }

            //分页查询
            //当前页数
            String pageNum = searchMap.get("pageNum");
            if(StringUtils.isEmpty(searchMap.get("pageNum"))){
                pageNum = "1";
            }
            //页数从O开始需要减一
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.valueOf(pageNum)-1, Page.pageSize));

            //执行查询,并处理结果集
            AggregatedPage<SkuInfo> aggregatedPage = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {

                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    ArrayList<T> list = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            //查询结果封装到SkuInfo
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            //获取高亮的属性
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if(highlightFields!=null&&highlightFields.get("name")!=null){
                                //返回结果设置高亮
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].string());
                            }

                            list.add((T) skuInfo);
                        }
                    }
                    //返回查询分页对象
                    return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //设置总条数
            resultMap.put("total",aggregatedPage.getTotalElements());
            //设置分页数
            resultMap.put("totalPages", aggregatedPage.getTotalPages());
            //设置查询结果集
            resultMap.put("rows",aggregatedPage.getContent());

            //获取品牌聚合结果
            StringTerms stringTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
            List<String> brandList = stringTerms.getBuckets().stream()
                    .map(bucket -> bucket.getKeyAsString())
                    .collect(Collectors.toList());
            resultMap.put("brandList",brandList);

            //获取规格聚合结果
            StringTerms specTerms = (StringTerms)aggregatedPage.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket
                    .getKeyAsString()).collect(Collectors.toList());

            resultMap.put("specList",formartSpec(specList));

            //设置页数
            resultMap.put("pageNum",pageNum);


            return resultMap;
        }

        return null;
    }

    /**
     * 原有数据
     *  [
     *         "{'颜色': '黑色', '尺码': '平光防蓝光-无度数电脑手机护目镜'}",
     *         "{'颜色': '红色', '尺码': '150度'}",
     *         "{'颜色': '黑色', '尺码': '150度'}",
     *         "{'颜色': '黑色'}",
     *         "{'颜色': '红色', '尺码': '100度'}",
     *         "{'颜色': '红色', '尺码': '250度'}",
     *         "{'颜色': '红色', '尺码': '350度'}",
     *         "{'颜色': '黑色', '尺码': '200度'}",
     *         "{'颜色': '黑色', '尺码': '250度'}"
     *     ]
     *
     *    需要的数据格式
     *    {
     *        颜色:[黑色,红色],
     *        尺码:[100度,150度]
     *    }
     * @param specList
     * @return
     */
    private Map<String, Set<String>> formartSpec(List<String> specList){
        Map<String,Set<String>> resultMap = new HashMap<>(16);
        if (specList!=null && specList.size()>0){
            for (String specJsonString : specList) {
                //将json数据转换为map
                Map<String,String> specMap = JSON.parseObject(specJsonString, Map.class);
                for (String specKey : specMap.keySet()) {
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet == null){
                        specSet = new HashSet<String>();
                    }
                    //将规格的值放入set中
                    specSet.add(specMap.get(specKey));
                    //将set放入map中
                    resultMap.put(specKey,specSet);
                }
            }
        }
        return resultMap;
    }
}
